package net.hzlj.platform.enterprise.utils.recorder;

import java.io.File;
import java.util.UUID;

/**
 * Created by Administrator on 2016/8/22 0022.
 */
public class WavRecorderAudioImpl implements RecorderAudioService {

    private ExtAudioRecorder mRecorder;
    private File mDir;// 保存录音的文件夹
    private String mCurrentFilePath;// 录音文件path
    private boolean isPrepared;// 是否已经准备完毕
    private RecorderAudioManager.AudioStateListener mListener;


    @Override
    public void setOnAudioStateListener(RecorderAudioManager.AudioStateListener listener) {
        this.mListener = listener;
    }

    @Override
    public void setRecorderFileDir(File dir) {
        this.mDir = dir;
    }


    @Override
    public void prepareAudio() {
        try {
            isPrepared = false;
            String fileName = generateFileName();
            File file = new File(mDir, fileName);
            mCurrentFilePath = file.getAbsolutePath();

            mRecorder = ExtAudioRecorder.getInstanse(false);
            mRecorder.setOutputFile(mCurrentFilePath);
            mRecorder.prepare();
            mRecorder.start();
            isPrepared = true;// 准备结束

            if (null != mListener) {
                mListener.wellPrepared();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void release() {
        try{
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }catch (Exception e){
            e.printStackTrace();
            mRecorder = null;
        }
    }

    @Override
    public void cancel() {
        if (null != mCurrentFilePath) {
            File file = new File(mCurrentFilePath);
            file.delete();
            mCurrentFilePath = null;
        }
        release();
    }

    @Override
    public String getCurrentFilePath() {
        return mCurrentFilePath;
    }

    @Override
    public int getVoiceLevel(int maxLevel) {
        int level = 1;
        if (isPrepared && null != mRecorder) {
            // 获得它最大的震幅 getMaxAmplitude()范围是1~32767
            level = mRecorder.getMaxAmplitude();
        }
        return level;
    }

    /**
     * 随机生成文件名称
     *
     * @return
     */
    private String generateFileName() {
        return UUID.randomUUID().toString() + ".wav";
    }

}
